package com.me.mysqladmin.controller;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.me.mysqladmin.entity.DataBase;
import com.me.mysqladmin.service.DataBaseService;
import com.me.mysqladmin.util.EasyUIFormat;

@Controller
@RequestMapping("/database")
public class DatabaseController extends BaseController {
	// 注入业务组件
	@Resource
	private DataBaseService dataBaseService;
	
	/**
	 * 打开主页，显示所有数据库和服务器地址
	 */
	@RequestMapping("/index.do")
	public String toIndex(){
		return "main/database";
	}
	
	/**
	 * 树形列表展示数据库和表
	 */
	@RequestMapping("/queryTree.do")
	@ResponseBody
	public List<Map<String, Object>> listTree(){
		LOG.info("---------------查询数据库列表树---------------");
		Map<String, List<String>> dbTree = dataBaseService.queryDbTree();
		return EasyUIFormat.parseTree(dbTree);
	}
	
	/**
	 * 查询所有数据库
	 */
	@RequestMapping("/queryPage.do")
	@ResponseBody
	public Map<String, Object> queryAll(){
		List<Map<String, Object>> databases = dataBaseService.showDatabases();
		return EasyUIFormat.parseGrid(databases, LinkedHashMap.class);
	}
	
	/**
	 * 创建数据库
	 */
	@RequestMapping("/insert.do")
	@ResponseBody
	public Map<String, Object> insert(DataBase database){
		try {
			LOG.info("--------创建数据库：" + database.getSchema_name() + "--------");
			Integer line = dataBaseService.createDatabase(database);
			return messageSuccess(line);
		} catch (Exception e) {
			return messageFailure(e.getMessage(), "创建数据库失败！");
		}
	}
	
	/**
	 * 删除数据库
	 */
	@RequestMapping("/delete.do")
	@ResponseBody
	public Map<String, Object> delete(DataBase database){
		try {
			LOG.info("--------删除数据库：" + database.getSchema_name() + "--------");
			dataBaseService.deleteDatabase(database);
			return messageSuccess();
		} catch (Exception e) {
			return messageFailure(e.getMessage(), "删除数据库失败！");
		}
	}
}
